{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-16T08:55:55.524400Z",
     "start_time": "2025-10-16T08:55:55.278126Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "\n",
    "from zsl_ma.models.projection import AttributeProjectionModel, FeatureProjectionModel\n",
    "import torch\n",
    "w = torch.load(r'D:\\Code\\2-ZSL\\1-output\\论文实验结果\\T04\\exp-2\\checkpoints\\semantic_projection.pth')\n",
    "model = AttributeProjectionModel(64, num_classes=2)\n",
    "model.load_state_dict(w)\n"
   ],
   "id": "3c5a47aafa202e12",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "df = pd.read_csv(r'D:\\Code\\2-ZSL\\1-output\\特征解耦结果\\exp-3\\train_disent.csv')\n",
    "df"
   ],
   "id": "973c0ccb9396d7e0",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-16T08:55:59.238270Z",
     "start_time": "2025-10-16T08:55:59.216790Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "npy_file_path = r'D:\\Code\\2-ZSL\\1-output\\论文实验结果\\T04\\exp-2\\attributes\\overall_feature_extraction\\train-Fault Location.npy'\n",
    "numpy_data = np.load(npy_file_path)\n",
    "# numpy_data\n",
    "tensor_data = torch.from_numpy(numpy_data).float()"
   ],
   "id": "d1f9b546afce2b5a",
   "outputs": [],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-16T08:56:01.137758Z",
     "start_time": "2025-10-16T08:56:01.133089Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from torch.utils import data\n",
    "\n",
    "dataset = data.TensorDataset(tensor_data)\n",
    "data_loader = data.DataLoader(\n",
    "        dataset,\n",
    "        batch_size=1000,\n",
    "        shuffle=False,  # 推理时通常不打乱数据\n",
    "    )\n"
   ],
   "id": "383c262ceaa7bfcb",
   "outputs": [],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "from torchvision import transforms\n",
    "transform= transforms.Compose([  # 用default_factory创建Compose实例\n",
    "            transforms.Resize((64, 64)),\n",
    "            transforms.ToTensor(),\n",
    "            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n",
    "        ])"
   ],
   "id": "ac5eb6df8f043921",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "from PIL import Image\n",
    "from tqdm import tqdm\n",
    "from zsl_ma.tools.tool import get_device\n",
    "device =  get_device()\n",
    "batch_size = 100\n",
    "model = model.to(device)\n",
    "total_samples = len(df)\n",
    "all_outputs = []\n",
    "for batch_start in tqdm(range(0, total_samples, batch_size)):\n",
    "    batch_end = min(batch_start + batch_size, total_samples)\n",
    "    batch_df = df.iloc[batch_start:batch_end]\n",
    "\n",
    "        # 1. 读取并预处理图片：保持原逻辑\n",
    "    batch_imgs = []\n",
    "    for img_path in batch_df[\"图片路径\"].tolist():\n",
    "        img_pil = Image.open(img_path).convert(\"RGB\")\n",
    "        img_tensor = transform(img_pil)\n",
    "        batch_imgs.append(img_tensor)\n",
    "    batch_tensor = torch.stack(batch_imgs, dim=0).to(device)  # shape: [batch_size, C, H, W]\n",
    "\n",
    "        # 2. 模型前向传播：保持原逻辑（获取图片特征）\n",
    "    outputs = model(batch_tensor)  # shape: [batch_size, feature_dim]\n",
    "    all_outputs.append(outputs)\n"
   ],
   "id": "714f9be6d2e43c82",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "final_output = torch.cat(all_outputs, dim=0)\n",
    "final_output = final_output.detach().cpu().numpy()\n",
    "np.save(r'D:\\Code\\2-ZSL\\1-output\\特征解耦结果\\exp-3\\attributes\\em\\特征嵌入.npy', final_output)"
   ],
   "id": "ebc4433543997208",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-16T08:56:13.122632Z",
     "start_time": "2025-10-16T08:56:11.726735Z"
    }
   },
   "cell_type": "code",
   "source": [
    "all_outputs = []\n",
    "with torch.no_grad():  # 推理时不需要计算梯度\n",
    "    for batch in data_loader:\n",
    "        inputs = batch[0]  # 获取批次数据\n",
    "        outputs,_ = model(inputs)  # 模型前向传播\n",
    "        all_outputs.append(outputs)\n",
    "\n",
    "    # 6. 合并所有输出\n",
    "final_output = torch.cat(all_outputs, dim=0)\n",
    "print(f\"模型输出形状: {final_output.shape}\")"
   ],
   "id": "3b375db7ad7339d6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "模型输出形状: torch.Size([8000, 512])\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-16T08:56:32.353578Z",
     "start_time": "2025-10-16T08:56:32.344837Z"
    }
   },
   "cell_type": "code",
   "source": "np.save(r'D:\\Code\\2-ZSL\\1-output\\论文实验结果\\T04\\exp-2\\attributes\\semantic_embed\\Fault Location_em.npy', final_output)",
   "id": "eb828658ef027387",
   "outputs": [],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "data = np.load(r'D:\\Code\\2-ZSL\\1-output\\特征解耦结果\\exp-3\\attributes\\em\\Fault Location_em.npy')\n",
    "data"
   ],
   "id": "d44935e24eb72204",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "import os\n",
    "from zsl_ma.tools.plot import visualize_features\n",
    "save_dir = r'D:\\Code\\2-ZSL\\1-output\\特征解耦结果\\exp-3'\n",
    "visualize_features(os.path.join(save_dir, 'attributes','em','Fault Location_em.npy'),\n",
    "                        os.path.join(save_dir, f'train_disent.csv'), 'Fault Location',\n",
    "                        os.path.join(save_dir, 'images',f'公共空间中的语义嵌入.jpg'),\n",
    "                   visualization_type='centers_only')"
   ],
   "id": "95715a01081fc915",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "from zsl_ma.tools.tool import get_device\n",
    "from zsl_ma.models.CNN import create_resnet\n",
    "import os\n",
    "device =  get_device()\n",
    "\n",
    "model = create_resnet(weight_path=os.path.join(save_dir, 'checkpoints','resnet50.pth'))"
   ],
   "id": "3efd37f4ea69a890",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "from torchvision.models.feature_extraction import create_feature_extractor\n",
    "target_layers = {\n",
    "    'avgpool': 'output',\n",
    "}\n",
    "model = create_feature_extractor(model, return_nodes=target_layers).to(device)\n",
    "model = model.to(device)"
   ],
   "id": "b41d736fc1298243",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "from torchvision import transforms\n",
    "from zsl_ma.tools.predict_untils import extract_features\n",
    "transform=  transforms.Compose([  # 用default_factory创建Compose实例\n",
    "            transforms.Resize((64, 64)),\n",
    "            transforms.ToTensor(),\n",
    "            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n",
    "        ])\n",
    "image_df, feature_matrix=extract_features(model=model,\n",
    "                 device=device,\n",
    "                 transform=transform,\n",
    "                 image_subdir='train',\n",
    "                 data_dir=r'D:\\Code\\2-ZSL\\0-data\\CWRU\\CWRU',\n",
    "                                          test_image_class=r'D:\\Code\\2-ZSL\\0-data\\CWRU\\CWRU\\seen_classes.txt',\n",
    "                                          batch_size=500\n",
    "                 )\n",
    "feature_matrix"
   ],
   "id": "94ef870cc882bd80",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "np.save(r'D:\\Code\\2-ZSL\\1-output\\特征解耦结果\\exp-3\\attributes\\em\\特征.npy', feature_matrix)"
   ],
   "id": "74353130df83971f",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "image_df.to_csv(r'D:\\Code\\2-ZSL\\1-output\\特征解耦结果\\exp-3\\论文.csv', index=False, encoding='utf-8-sig')",
   "id": "b829d87299a9462c",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "324de054935d8eed"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
